import { useContext } from 'react';

// todo: оставить одну модалку для отзыва
import { ratingApi } from '@/entities/rating';
import { ModalContext } from '@/shared/context/ModalContext';
import { Button, ButtonVariants, Modal, Snackbar, Title } from '@/shared/ui';
import { useSnackbar } from 'notistack';
import { useWindowSize } from 'usehooks-ts';

import cs from './SendReviewModal.module.scss';

export const SendReviewModal = () => {
  const { width } = useWindowSize();
  const { closeModal, data, setData } = useContext(ModalContext);
  const [mutation, { isSuccess, error }] = ratingApi.useAddProductRatingMutation();
  const { enqueueSnackbar } = useSnackbar();
  const handleClose = () => {
    closeModal();
  };
  const handleCloseWithNullData = () => {
    setData(() => ({ check: 'exit' }));
    closeModal();
  };
  const sendData = () => {
    mutation(data).then(() => {
      const snack: { variant: 'error' | 'success'; message: string } = isSuccess
        ? { variant: 'success', message: 'Отзыв отправлен' }
        : { variant: 'error', message: 'Отзыв не отправлен' };
      enqueueSnackbar(snack.message, {
        variant: snack.variant,
        content: (key, message) => <Snackbar id={key} message={message} size="md" variant={snack.variant} />,
      });
      if (error) {
        // console.error(error);
      }
      if (isSuccess) {
        handleCloseWithNullData();
      }
    });
  };

  return (
    <Modal isOpen onCloseClick={handleClose} zIndex={1002}>
      <div className={cs.modal}>
        <Title size="l" tag="h3">
          Отправить отзыв?
        </Title>
        <div className={cs.content}>
          <Button className={cs.send} onClick={() => sendData()} variant={ButtonVariants.Primary}>
            Отправить
          </Button>
          <button className={cs.decline} onClick={handleCloseWithNullData} type="button">
            Не отправлять
          </button>
        </div>
      </div>
    </Modal>
  );
};
